package com.m4f.city.web.controller.api;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.m4f.city.business.domain.InternalUser;
import com.m4f.city.business.domain.Organization;
import com.m4f.city.utils.serializer.M4FJsonSerializer;

@Controller
@RequestMapping("/api/organization")
public class OrganizationApiController extends ApiBaseController {
		
	@RequestMapping("/info")
	@ResponseBody
	public Map<String, Object> getOrganizationInfo(Principal principal, HttpServletResponse response) throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		InternalUser user = null;
		Organization organization = null;
		
		if(principal instanceof OAuth2Authentication) {
			OAuth2Authentication auth = (OAuth2Authentication) principal;
			user = (InternalUser) auth.getUserAuthentication().getPrincipal();
			organization = this.serviceLocator.getOrganizationService().getOrganization(user.getOrganizationId());
		} else {
			throw new Exception("You are not using oauth!"); // TODO create a m4f exception!!!!
		}
		
		if(organization != null) {
			M4FJsonSerializer serializer = new M4FJsonSerializer(); // TODO inject!
			map = serializer.getMap(organization);
		}
		
		return map;
	}
}
